package com.gears_software.sxdc.dccx.ui.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.nearby.NearbyInfo;
import com.amap.api.services.nearby.NearbySearch;
import com.amap.api.services.nearby.NearbySearchFunctionType;
import com.amap.api.services.nearby.NearbySearchResult;
import com.amap.api.services.nearby.UploadInfo;
import com.amap.api.services.nearby.UploadInfoCallback;
import com.bigkoo.pickerview.OptionsPickerView;
import com.gears_software.sxdc.dccx.R;
import com.gears_software.sxdc.dccx.application.DCCXApplication;
import com.gears_software.sxdc.dccx.data.finder.IBaseFinder;
import com.gears_software.sxdc.dccx.data.finder.IZPOrderFinder;
import com.gears_software.sxdc.dccx.data.finder.util.GearsErrorHandler;
import com.gears_software.sxdc.dccx.data.model.AddZPOrderModel;
import com.gears_software.sxdc.dccx.data.model.EstimateModel;
import com.gears_software.sxdc.dccx.data.model.PositionEntity;
import com.gears_software.sxdc.dccx.data.model.ResultModel;
import com.gears_software.sxdc.dccx.data.model.TypeModel;
import com.gears_software.sxdc.dccx.data.model.YunTuApiDataModel;
import com.gears_software.sxdc.dccx.data.model.YunTuApiModel;
import com.gears_software.sxdc.dccx.data.model.ZPOrderModel;
import com.gears_software.sxdc.dccx.data.model.request.RZEstimate;
import com.gears_software.sxdc.dccx.data.model.request.RZPOrderModel;
import com.gears_software.sxdc.dccx.data.sharedPreference.DCCXSp_;
import com.gears_software.sxdc.dccx.ui.activity.AddCarInfoActivity_;
import com.gears_software.sxdc.dccx.ui.activity.DestinationActivity_;
import com.gears_software.sxdc.dccx.ui.activity.JieSongJiActivity_;
import com.gears_software.sxdc.dccx.ui.activity.LoginActivity_;
import com.gears_software.sxdc.dccx.ui.activity.MainActivity;
import com.gears_software.sxdc.dccx.ui.activity.RelpaceCallCarActivity;
import com.gears_software.sxdc.dccx.ui.activity.RelpaceCallCarActivity_;
import com.gears_software.sxdc.dccx.ui.activity.WaitForJieJiaActivity;
import com.gears_software.sxdc.dccx.ui.activity.WaitForJieJiaActivity_;
import com.gears_software.sxdc.dccx.ui.activity.WaitForJieJiaNewActivity_;
import com.gears_software.sxdc.dccx.ui.activity.YuYueActivity_;
import com.gears_software.sxdc.dccx.ui.event.IsAutoLocationEvent;
import com.gears_software.sxdc.dccx.ui.map.LocationTask;
import com.gears_software.sxdc.dccx.ui.map.OnLocationGetListener;
import com.gears_software.sxdc.dccx.ui.map.RegeocodeTask;
import com.gears_software.sxdc.dccx.ui.map.RouteTask;
import com.gears_software.sxdc.dccx.ui.util.OttoBus;
import com.orhanobut.logger.Logger;
import com.sdsmdg.tastytoast.TastyToast;
import com.squareup.otto.Subscribe;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.androidannotations.ormlite.annotations.OrmLiteDao;
import org.androidannotations.rest.spring.annotations.RestService;

import java.lang.reflect.Array;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import anet.channel.util.Utils;


/**
 * Created by chezhenzhen on 2017/6/27.
 * 专车
 */

@EFragment
public class SpecialCarFragment extends Fragment implements AMap.OnMapTouchListener, AMap.OnMapLoadedListener, LocationSource, AMap.OnCameraChangeListener, OnLocationGetListener, RouteTask.OnRouteCalculateListener, NearbySearch.NearbyListener {

    @Pref
    DCCXSp_ sp;
    @App
    DCCXApplication app;
    @RestService
    IBaseFinder baseFinder;
    @RestService
    IZPOrderFinder zpOrderFinder;
    @Bean
    GearsErrorHandler errorHandler;
    MapView mMapView;
    TextView txt_yuyue;
    TextView txt_yongche;
    TextView txt_jiesongji;
    TextView txt_location;
    TextView txt_start;
    TextView txt_shang;
    TextView txt_xia;
    TextView txt_cartype_icon;
    TextView txt_address;
    LinearLayout fromto_container;
    LinearLayout ly_location;
    LinearLayout ly_ingorder;
    TextView txt_shang_address;
    TextView txt_xia_address;
    TextView txt_yugu;
    TextView txt_distance;
    TextView txt_duration;
    TextView txt_cartype;
    TextView txt_youhui;
    TextView txt_juan_show;
    TextView txt_yuan;
    RadioGroup radio_group;
    RadioButton rb_gw;
    RadioButton rb_sw;
    RadioButton rb_hh;
    RelativeLayout re_xiache;
    RelativeLayout re_shangche;
    LinearLayout ly_bottom_menu;
    LinearLayout ly_usecar;
    RelativeLayout re_yongche;
    RelativeLayout ly_yugujia;
    RelativeLayout re_jiesongji;
    RelativeLayout re_yuyue;
    RelativeLayout re_cartype;
    Button btn_callCar;
    Button btn_replace;
    ImageView moveIcon;

    //地图对象
    AMap aMap;
    private LocationTask mLocationTask;
    private RegeocodeTask mRegeocodeTask;
    private OnLocationChangedListener mListener = null;//定位监听器

    private LatLng mStartPosition;//起点
    private LatLng mEndPosition;//终点
    private boolean mIsFirst = true; //用于判断地图是不是第一次定位返回，拖拽地图不回到定位点用的
    public boolean isFirst = true; //用于监听后退改变状态
    public boolean isNearBy = true; //用于判断是否搜索附近车辆
    private boolean isChangeStartAddress = true; //用于判断下车地返回时不允许地图拖拽，改变上车地位置
    private boolean isStart = true; //用于判断上车地是不是通过选择返回的；
    PositionEntity startEntity;
    AMapLocation aMapLocation;
    private Marker mEndLocationMark;//终点marker
    private Marker mStartLocationMark;//起点marker
    private static ArrayList<Marker> markers = new ArrayList<Marker>(); //用于存放起点终点的marker
    private ArrayList<Marker> carMarkers = new ArrayList<Marker>(); //用于汽车打点存放的marker

    NearbySearch mNearbySearch;
    OptionsPickerView pickerView;
    String cartype;
    float distance; //距离 km
    int duration;  //时长 分
    List<NearbyInfo> nearList = new ArrayList<NearbyInfo>();
    String adCode = "";
    String yuntuKey = "e85f18461e5294541a0845f71897dec2";
    List<LatLonPoint> nearCarList = new ArrayList<LatLonPoint>();
    ZPOrderModel zpOrderModel;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_specialcar, null);
        mMapView = (MapView) view.findViewById(R.id.mMapView);
        txt_yuyue = (TextView) view.findViewById(R.id.txt_yuyue);
        txt_yongche = (TextView) view.findViewById(R.id.txt_yongche);
        txt_jiesongji = (TextView) view.findViewById(R.id.txt_jiesongji);
        txt_location = (TextView) view.findViewById(R.id.txt_location);
        txt_start = (TextView) view.findViewById(R.id.txt_start);
        txt_shang = (TextView) view.findViewById(R.id.txt_shang);
        txt_xia = (TextView) view.findViewById(R.id.txt_xia);
        txt_cartype_icon = (TextView) view.findViewById(R.id.txt_cartype_icon);
        txt_address = (TextView) view.findViewById(R.id.txt_address);
        fromto_container = (LinearLayout) view.findViewById(R.id.fromto_container);
        ly_ingorder = (LinearLayout) view.findViewById(R.id.ly_ingorder);
        ly_location = (LinearLayout) view.findViewById(R.id.ly_location);
        txt_shang_address = (TextView) view.findViewById(R.id.txt_shang_address);
        txt_xia_address = (TextView) view.findViewById(R.id.txt_xia_address);
        txt_yugu = (TextView) view.findViewById(R.id.txt_yugu);
        txt_cartype = (TextView) view.findViewById(R.id.txt_cartype);
        txt_youhui = (TextView) view.findViewById(R.id.txt_youhui);
        txt_juan_show = (TextView) view.findViewById(R.id.txt_juan_show);
        txt_yuan = (TextView) view.findViewById(R.id.txt_yuan);
        radio_group = (RadioGroup) view.findViewById(R.id.radio_group);
        rb_gw = (RadioButton) view.findViewById(R.id.rb_gw);
        rb_sw = (RadioButton) view.findViewById(R.id.rb_sw);
        rb_hh = (RadioButton) view.findViewById(R.id.rb_hh);
        re_xiache = (RelativeLayout) view.findViewById(R.id.re_xiache);
        re_shangche = (RelativeLayout) view.findViewById(R.id.re_shangche);
        ly_bottom_menu = (LinearLayout) view.findViewById(R.id.ly_bottom_menu);
        ly_usecar = (LinearLayout) view.findViewById(R.id.ly_usecar);
        re_yongche = (RelativeLayout) view.findViewById(R.id.re_yongche);
        ly_yugujia = (RelativeLayout) view.findViewById(R.id.ly_yugujia);
        re_jiesongji = (RelativeLayout) view.findViewById(R.id.re_jiesongji);
        re_yuyue = (RelativeLayout) view.findViewById(R.id.re_yuyue);
        txt_distance = (TextView) view.findViewById(R.id.txt_distance);
        txt_duration = (TextView) view.findViewById(R.id.txt_duration);
        re_cartype = (RelativeLayout) view.findViewById(R.id.re_cartype);
        btn_callCar = (Button) view.findViewById(R.id.btn_callCar);
        btn_replace = (Button) view.findViewById(R.id.btn_replace);
        moveIcon = (ImageView) view.findViewById(R.id.img_move_icon);
        initIconFont();
        baseFinder.setRestErrorHandler(errorHandler);
        zpOrderFinder.setRestErrorHandler(errorHandler);
        mLocationTask = new LocationTask(getActivity());
        mLocationTask.setOnLocationGetListener(this);
        mRegeocodeTask = new RegeocodeTask(getContext());
        RouteTask.getInstance(getContext()).addRouteCalculateListener(this);
        //获取附近实例（单例模式）
        mNearbySearch = NearbySearch.getInstance(getContext());
        //设置附近监听
        mNearbySearch.addNearbyListener(this);
        mMapView.onCreate(savedInstanceState);
        initMap();
        isIngOrder();
        return view;
    }

    void initMap() {
        if (aMap == null) {
            aMap = mMapView.getMap();
        }

        aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
        //设置显示定位按钮 并且可以点击
        UiSettings settings = aMap.getUiSettings();
        //地图上不显示放大缩小按钮
        settings.setZoomControlsEnabled(false);
        // 是否显示定位按钮
        settings.setMyLocationButtonEnabled(false);

        //设置定位监听
        aMap.setLocationSource(this);
        //是否可触发定位并显示定位层
        aMap.setMyLocationEnabled(true);
        //定位的小图标 默认是蓝点 其实就是一张图片
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromBitmap(mergeBitmap()));
//        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.gps1));
        myLocationStyle.radiusFillColor(android.R.color.transparent);
        myLocationStyle.strokeColor(android.R.color.transparent);
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);
        aMap.setMyLocationStyle(myLocationStyle);

        aMap.setOnMapLoadedListener(this);
        aMap.setOnCameraChangeListener(this);
        aMap.setOnMapTouchListener(this);
    }

    public Bitmap mergeBitmap() {
        Bitmap bitmap1 = ((BitmapDrawable) getResources().getDrawable(
                R.mipmap.aj1)).getBitmap();
        Bitmap bitmap2 = ((BitmapDrawable) getResources().getDrawable(
                R.mipmap.aj2)).getBitmap();

        Bitmap bitmap = Bitmap.createBitmap(bitmap1.getWidth(), bitmap1.getHeight(), bitmap1.getConfig());
        Canvas canvas = new Canvas(bitmap);
        canvas.drawBitmap(bitmap1, new Matrix(), null);
        canvas.drawBitmap(bitmap2, 0, 0, null);
        return bitmap;
    }


    void initIconFont() {
        txt_yuyue.setTypeface(app.iconfont);
        txt_yongche.setTypeface(app.iconfont);
        txt_jiesongji.setTypeface(app.iconfont);
        txt_location.setTypeface(app.iconfont);
        txt_start.setTypeface(app.iconfont);
        txt_shang.setTypeface(app.iconfont);
        txt_xia.setTypeface(app.iconfont);
        txt_cartype_icon.setTypeface(app.iconfont);
    }

    public void isIngOrder() {
//        String orderid = sp.orderid().get();
//        Logger.d("*****" + orderid);
//        if (orderid != null && !orderid.equals("0")) {
//            getIngOrder();
//        } else {
//            ly_ingorder.setVisibility(View.GONE);
//        }

        if (!sp.token().get().equals("")){
            getIngOrder();
        }
    }

    @Background
    void getIngOrder() {
        ResultModel<ZPOrderModel> res = zpOrderFinder.getIngOrder();
        showIngResult(res);
    }

    @UiThread
    void showIngResult(ResultModel<ZPOrderModel> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                if (res.getData() != null) {
                    ly_ingorder.setVisibility(View.VISIBLE);
                    zpOrderModel = res.getData();
                    mStartPosition = new LatLng(Double.parseDouble(zpOrderModel.getDeplatitude().toString()), Double.parseDouble(zpOrderModel.getDeplongitude().toString()));
                    mEndPosition = new LatLng(Double.parseDouble(zpOrderModel.getDestlatitude().toString()), Double.parseDouble(zpOrderModel.getDestlongitude().toString()));
//                    Date date = sendOrders.getOrdertime();
//                    DateFormat df = new SimpleDateFormat("hh:mm");
//                    String str = df.format(date);
//                    tv_time.setText("今天:"+str);
//                    tv_qidian.setText(sendOrders.getDeparture());
//                    tv_zhongdian.setText(sendOrders.getDestination());
                }
            } else {
                sp.orderid().put("0");
                ly_ingorder.setVisibility(View.GONE);
            }
        }
    }

    @Click
    void ly_ingorder() {
        Intent intent = new Intent(getActivity(), WaitForJieJiaNewActivity_.class);
//        intent.putExtra("mStartPosition", mStartPosition);
//        intent.putExtra("mEndPosition", mEndPosition);
        intent.putExtra("orderModelDetail", zpOrderModel);
        startActivity(intent);
    }

    @Override
    public void onMapLoaded() {
        Logger.d("地图加载");
//        mLocationTask.startLocate(8);
    }


    private void hideView() {
        fromto_container.setVisibility(View.GONE);
    }

    private void showView() {
        fromto_container.setVisibility(View.VISIBLE);

    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
        if (isChangeStartAddress) {
            hideView();
            txt_shang_address.setText("正在定位上车地点");
        }

    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        if (isFirst) {
            showView();
        } else {
            hideView();
        }
        if (mIsFirst) {

        } else {
            mLocationTask.stopLocate();
        }

        if (isChangeStartAddress) {
            mStartPosition = cameraPosition.target;
            mRegeocodeTask.setOnLocationGetListener(this);
            mRegeocodeTask.search(mStartPosition.latitude, mStartPosition.longitude);
        }

    }

    @Override
    public void onLocationGet(final PositionEntity entity, AMapLocation aMapLocation) {
        Logger.d(entity.getLatitue() + "        " + entity.getLongitude());
        Logger.d("连续定位");
        adCode = aMapLocation.getAdCode();
        String address = entity.getAddress().replace(entity.getProvince(), "").replace(entity.getCity(), "").replace(entity.getDistrict(), "");
        txt_address.setText(entity.getAddress());
        txt_shang_address.setText(address);
        startEntity = entity;
        if (isNearBy) {
//            nearSearch(entity.getLatitue(), entity.getLongitude());
            nearSearchCar(entity.getLatitue(), entity.getLongitude());
        }
        RouteTask.getInstance(getContext()).setStartPoint(entity);
        mStartPosition = new LatLng(entity.getLatitue(), entity.getLongitude());
        this.aMapLocation = aMapLocation;

        if (mIsFirst) {
//            CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(mStartPosition, 17);
//            aMap.animateCamera(cameraUpdate);
            //设置缩放级别
            aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
            //将地图移动到定位点
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(mStartPosition));
            mListener.onLocationChanged(aMapLocation);
//            mIsFirst = false;
        }

    }

    @Override
    public void onRegecodeGet(PositionEntity entity) {
        String address = entity.getAddress().replace(entity.getProvince(), "").replace(entity.getCity(), "").replace(entity.getDistrict(), "");
        txt_address.setText(entity.getAddress());
        adCode = entity.getAdCode();
        txt_shang_address.setText(address);
        entity.setLatitue(mStartPosition.latitude);
        entity.setLongitude(mStartPosition.longitude);
        startEntity = entity;
        RouteTask.getInstance(getContext()).setStartPoint(entity);
        RouteTask.getInstance(getContext()).search();
    }

    @Background
    void nearSearchCar(double latitue, double longitude) {
        String center = String.valueOf(longitude) + "," + String.valueOf(latitue);
        YunTuApiModel apiModel = zpOrderFinder.getYunTuApi(yuntuKey, center, "3000", "1", "60");
        showNearSearchResult(apiModel);
    }

    @UiThread
    void showNearSearchResult(YunTuApiModel apiModel) {
        if (apiModel != null) {
            if (apiModel.getStatus() != null && apiModel.getStatus().equals("1")) {
                Logger.d("周边云图搜索，个数" + apiModel.getCount());
                if (apiModel.getDatas() != null) {
                    List<YunTuApiDataModel> dataModel = apiModel.getDatas();
                    if (dataModel.size() > 0) {
                        nearCarList.clear();
                        for (int i = 0; i < dataModel.size(); i++) {
                            String[] location = dataModel.get(i).getLocation().split(",");
                            double lon = Double.parseDouble(location[0].toString());
                            double lat = Double.parseDouble(location[1].toString());
                            nearCarList.add(new LatLonPoint(lat, lon));
                        }
                    } else {
                        nearCarList.clear();
                    }
                    addEmulateData();
                }

            }
        }
    }

    //暂时不用这种方式获取车辆位置
    private void nearSearch(double latitue, double longitude) {
        //设置搜索条件
        NearbySearch.NearbyQuery query = new NearbySearch.NearbyQuery();
        //设置搜索的中心点
        query.setCenterPoint(new LatLonPoint(latitue, longitude));
        //设置搜索的坐标体系
        query.setCoordType(NearbySearch.AMAP);
        //设置搜索半径
        query.setRadius(1000);
        //设置查询的时间
        query.setTimeRange(30);
        //设置查询的方式驾车还是距离
        query.setType(NearbySearchFunctionType.DRIVING_DISTANCE_SEARCH);
        //调用异步查询接口
        NearbySearch.getInstance(getContext())
                .searchNearbyInfoAsyn(query);
    }

    @Click
    void ly_location() {
        mIsFirst = true;
        mLocationTask.startLocate(8);
//        mListener.onLocationChanged(aMapLocation);
    }

    @Click
    void re_yongche() {
        if (!sp.token().get().equals("")) {
            isFirst = false;
            fromto_container.setVisibility(View.INVISIBLE);
            ly_bottom_menu.setVisibility(View.GONE);
            ly_usecar.setVisibility(View.VISIBLE);
            ((MainActivity) getContext()).back_icon.setText(R.string.back_icon);
            ((MainActivity) getContext()).actionbar_title.setText("我要用车");
            ((MainActivity) getContext()).right_icon.setVisibility(View.INVISIBLE);
            getCarType();
        } else {
            Intent intent = new Intent(getActivity(), LoginActivity_.class);
            startActivity(intent);
        }
    }

    public void modifyState() {
        isFirst = true;
        isNearBy = true;
        isChangeStartAddress = true;
        isStart = true;
        re_xiache.setEnabled(true);
        re_shangche.setEnabled(true);
        moveIcon.setVisibility(View.VISIBLE);
        removeMarkers(markers);

        mIsFirst = true;
        mLocationTask.startLocate(8);

//        aMap.setPointToCenter(mMapView.getWidth() / 2, mMapView.getHeight() / 2);

//        //设置缩放级别
        aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
//        //将地图移动到定位点
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(mStartPosition));
        ly_bottom_menu.setVisibility(View.VISIBLE);
        ly_usecar.setVisibility(View.GONE);
        ((MainActivity) getContext()).back_icon.setText(R.string.my_icon);
        ((MainActivity) getContext()).actionbar_title.setText("大昌出行");
        ((MainActivity) getContext()).right_icon.setVisibility(View.VISIBLE);
        fromto_container.setVisibility(View.VISIBLE);
        btn_callCar.setVisibility(View.GONE);
        btn_replace.setVisibility(View.GONE);
        ly_yugujia.setVisibility(View.GONE);
        txt_xia_address.setText("您在那儿下车");
        if (RouteTask.getInstance(getContext()).getEndPoint() != null) {
            RouteTask.getInstance(getContext()).clearEndPoint();
        }
    }

    @Click
    void re_yuyue() {
//        Intent intent = new Intent(getActivity(), YuYueActivity_.class);
//        intent.putExtra("startEntity", startEntity);
//        startActivity(intent);

        new MaterialDialog.Builder(getActivity())
                .title("提示")
                .titleGravity(GravityEnum.CENTER)
                .titleColorRes(R.color.colorFontGray)
                .content("敬请期待")
                .contentGravity(GravityEnum.CENTER)
                .contentColorRes(R.color.colorFontGray)
                .positiveText("确定")
                .positiveColor(ContextCompat.getColor(getActivity(), R.color.colorFontBlue))
                .buttonsGravity(GravityEnum.CENTER)
                .show();

    }

    @Click
    void re_shangche() {
        if (startEntity != null && startEntity.getCity() != null) {
            Intent intent = new Intent(getActivity(), DestinationActivity_.class);
            intent.putExtra("title", "选择上车地点");
            intent.putExtra("flag", "start");
            intent.putExtra("currentCity", startEntity.getCity());
            startActivityForResult(intent, 1);
        } else {
            TastyToast.makeText(getActivity(), "当前城市定位异常，请检查网络。", app.SHORT, app.WARNING);
        }

    }

    @Click
    void re_xiache() {
        if (startEntity != null && startEntity.getCity() != null) {
            Intent intent = new Intent(getActivity(), DestinationActivity_.class);
            intent.putExtra("title", "选择下车地点");
            intent.putExtra("flag", "end");
            intent.putExtra("currentCity", startEntity.getCity());
            startActivityForResult(intent, 2);
        } else {
            TastyToast.makeText(getActivity(), "当前城市定位异常，请检查网络。", app.SHORT, app.WARNING);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (data != null) {
                PositionEntity startEntity = (PositionEntity) data.getExtras().getSerializable("entity");
//                mLocationTask.stopLocate();
                isStart = false;
                mStartPosition = new LatLng(startEntity.getLatitue(), startEntity.getLongitude());
                if (startEntity.getName() != null && !startEntity.getName().equals("")) {
                    txt_shang_address.setText(startEntity.getName());
                }
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(mStartPosition));
                nearSearchCar(startEntity.getLatitue(), startEntity.getLongitude());

            }
        } else if (requestCode == 2) {
            if (data != null) {
                if (carMarkers.size() > 0) {
                    removeMarkers(carMarkers);
                }
                isNearBy = false;
                mIsFirst = false;
                PositionEntity entity = (PositionEntity) data.getExtras().getSerializable("entity");
                isChangeStartAddress = false;
                re_xiache.setEnabled(false);
                re_shangche.setEnabled(false);
                if (entity != null) {
                    mEndPosition = new LatLng(entity.getLatitue(), entity.getLongitude());
                    moveIcon.setVisibility(View.GONE);
                    addStartLocationMark();
                    addEndLocationMark();
                    List<LatLng> latLngs = new ArrayList<LatLng>();
                    latLngs.add(mStartPosition);
                    latLngs.add(mEndPosition);
                    zoomToSpan(latLngs);
                    if (entity.getName() != null && !entity.getName().equals("")) {
                        txt_xia_address.setText(entity.getName());
                        ly_yugujia.setVisibility(View.VISIBLE);
                        btn_callCar.setVisibility(View.VISIBLE);
                        btn_replace.setVisibility(View.VISIBLE);
                    }
                }

            }
        }
    }

    //根据屏幕的位置对路线进行适应屏幕的缩放
    private void zoomToSpan(List<LatLng> latLngs) {
        LatLngBounds.Builder b = LatLngBounds.builder();
        for (LatLng latLng : latLngs) {
            b.include(latLng);
        }
        LatLngBounds bounds = b.build();
        aMap.animateCamera(CameraUpdateFactory.newLatLngBoundsRect(bounds, 100, 100, 140, 700));
//        aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 450));
    }

    void addStartLocationMark() {
        MarkerOptions markerOptions = new MarkerOptions();
        if (mStartLocationMark == null) {
            markerOptions.icon(BitmapDescriptorFactory
                    .fromResource(R.mipmap.up))
                    .position(mStartPosition);
        } else {
            mStartLocationMark.remove();
            markerOptions.icon(BitmapDescriptorFactory
                    .fromResource(R.mipmap.up));
            markerOptions.position(mStartPosition);

        }
        mStartLocationMark = aMap.addMarker(markerOptions);
        markers.add(mStartLocationMark);

    }

    void addEndLocationMark() {
        MarkerOptions markerOptions = new MarkerOptions();
        if (mEndLocationMark == null) {
            markerOptions.icon(BitmapDescriptorFactory
                    .fromResource(R.mipmap.down))
                    .position(mEndPosition);
        } else {
            mEndLocationMark.remove();
            markerOptions.icon(BitmapDescriptorFactory
                    .fromResource(R.mipmap.down));
            markerOptions.position(mEndPosition);

        }
        mEndLocationMark = aMap.addMarker(markerOptions);
        markers.add(mEndLocationMark);
    }

    @Override
    public void onRouteCalculate(float cost, float distance, int duration) {
        this.distance = distance;
        this.duration = duration;
        Logger.d("费用： " + cost + "距离： " + distance + "用时： " + duration);
//        txt_yugu.setText(String.format("预估费用%.2f元，距离%.1fkm,用时%d分", cost, distance, duration));
        getEstimate(duration, distance);
    }

    @Background
    void getEstimate(int zTime, float zMile) {
        if (adCode == null || adCode.equals("")) {
            adCode = "140100";
        }
        int address = Integer.parseInt(adCode.substring(0, adCode.length() - 2) + "00");
        ResultModel<EstimateModel> res = zpOrderFinder.getEstimate(String.valueOf(zTime), String.valueOf(zMile), cartype, address);
        showEstimateResult(res, zTime, zMile);
    }

    @UiThread
    void showEstimateResult(ResultModel<EstimateModel> res, int zTime, float zMile) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                if (res.getData() != null) {
                    EstimateModel estimateModel = res.getData();
                    if (estimateModel.getPrice() != null && !estimateModel.getPrice().equals("")
                            && estimateModel.getDiscount() != null && !estimateModel.getDiscount().equals(""))
                        txt_yugu.setText(String.format("%.2f", Float.parseFloat(estimateModel.getPrice()) - Float.parseFloat(estimateModel.getDiscount())));
                    if (estimateModel.getDiscount().equals("0.00")) {
                        txt_juan_show.setVisibility(View.GONE);
                        txt_youhui.setVisibility(View.GONE);
                        txt_yuan.setVisibility(View.GONE);
                    } else {
                        txt_juan_show.setVisibility(View.VISIBLE);
                        txt_youhui.setVisibility(View.VISIBLE);
                        txt_yuan.setVisibility(View.VISIBLE);
                        txt_youhui.setText(String.format("%.2f", Float.parseFloat(estimateModel.getDiscount())));
                    }
                    txt_distance.setText(String.format("%.1fkm", zMile));
                    txt_duration.setText(String.format("%d分", zTime));
                }
            }
        }
    }

    @Override
    public void onUserInfoCleared(int i) {
        Logger.d("清除返回code: " + i);
    }

    @Override
    public void onNearbyInfoSearched(NearbySearchResult nearbySearchResult, int resultCode) {
        //搜索周边附近用户回调处理
        if (resultCode == 1000) {
            if (nearbySearchResult != null && nearbySearchResult.getNearbyInfoList() != null && nearbySearchResult.getNearbyInfoList().size() > 0) {
                NearbyInfo nearbyInfo = nearbySearchResult.getNearbyInfoList().get(0);
                nearList = nearbySearchResult.getNearbyInfoList();
                addEmulateData();
                Logger.d("周边搜索结果为size " + nearbySearchResult.getNearbyInfoList().size() +
                        " first：" + nearbyInfo.getUserID() + "  " + nearbyInfo.getDistance() + "  "
                        + nearbyInfo.getDrivingDistance() + "  " + nearbyInfo.getTimeStamp() + "  " + nearbyInfo.getPoint().toString());
            } else {
                Logger.d("周边搜索结果为空");
                if (carMarkers.size() > 0) {
                    removeMarkers(carMarkers);
                }
            }
        } else {
            Logger.d("周边搜索出现异常，异常码为：" + resultCode);

        }
    }

    public void addEmulateData() {
//        if (nearList != null && nearList.size() > 0) {
//            if (carMarkers.size() > 0) {
//                removeMarkers(carMarkers);
//            }
//            BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory
//                    .fromResource(R.mipmap.car_icon);
//            for (int i = 0; i < nearList.size(); i++) {
//                LatLonPoint latLonPoint = nearList.get(i).getPoint();
//                double latitudeDelt = latLonPoint.getLatitude();
//                double longtitudeDelt = latLonPoint.getLongitude();
//                MarkerOptions markerOptions = new MarkerOptions();
//                markerOptions.setFlat(true);
//                markerOptions.anchor(0.5f, 0.5f);
//                markerOptions.icon(bitmapDescriptor);
//                markerOptions.position(new LatLng(latitudeDelt, longtitudeDelt));
//                Marker marker = aMap.addMarker(markerOptions);
//                carMarkers.add(marker);
//            }
//        }
        if (nearCarList != null && nearCarList.size() > 0) {
            if (carMarkers.size() > 0) {
                removeMarkers(carMarkers);
            }
            BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory
                    .fromResource(R.mipmap.car_icon);
            for (int i = 0; i < nearCarList.size(); i++) {
                LatLonPoint latLonPoint = nearCarList.get(i);
                double latitudeDelt = latLonPoint.getLatitude();
                double longtitudeDelt = latLonPoint.getLongitude();
                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.setFlat(true);
                markerOptions.anchor(0.5f, 0.5f);
                markerOptions.icon(bitmapDescriptor);
                markerOptions.position(new LatLng(latitudeDelt, longtitudeDelt));
                Marker marker = aMap.addMarker(markerOptions);
                carMarkers.add(marker);
            }
        } else {
            if (carMarkers.size() > 0) {
                removeMarkers(carMarkers);
            }
        }
    }


    @Override
    public void onNearbyInfoUploaded(int i) {
        Logger.d("上传返回code：  " + i);
    }

    @Click
    void re_jiesongji() {
//        Intent intent = new Intent(getActivity(), JieSongJiActivity_.class);
//        intent.putExtra("currentCity", startEntity.getCity());
//        startActivity(intent);
        new MaterialDialog.Builder(getActivity())
                .title("提示")
                .titleGravity(GravityEnum.CENTER)
                .titleColorRes(R.color.colorFontGray)
                .content("敬请期待")
                .contentGravity(GravityEnum.CENTER)
                .contentColorRes(R.color.colorFontGray)
                .positiveText("确定")
                .positiveColor(ContextCompat.getColor(getActivity(), R.color.colorFontBlue))
                .buttonsGravity(GravityEnum.CENTER)
                .show();
    }

    @Click
    void re_cartype() {
        pickerView.show();
    }

    @Background
    void getCarType() {
        ResultModel<List<TypeModel>> res = baseFinder.getCarType();
        showCarTypeResult(res);
    }

    @UiThread
    void showCarTypeResult(ResultModel<List<TypeModel>> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                if (res.getData() != null) {
                    final List<TypeModel> carList = res.getData();
                    if (carList != null && carList.size() > 0) {
                        txt_cartype.setText(carList.get(0).getTypename());
                        cartype = carList.get(0).getTypecode();
                        Logger.d("cartype: " + cartype);
                        pickerView = new OptionsPickerView.Builder(getActivity(), new OptionsPickerView.OnOptionsSelectListener() {
                            @Override
                            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                                txt_cartype.setText(carList.get(options1).getTypename());
                                cartype = carList.get(options1).getTypecode();
                                if (distance != 0 && duration != 0) {
                                    getEstimate(duration, distance);
                                }
                            }
                        }).setLineSpacingMultiplier(2).build();
                        pickerView.setPicker(carList);
                    }
                }
            }
        }
    }

    @Click
    void btn_callCar() {
        if ((String.valueOf(mStartPosition.latitude) != null && !String.valueOf(mStartPosition.latitude).equals("")) || (String.valueOf(mStartPosition.longitude) != null && !String.valueOf(mStartPosition.longitude).equals(""))) {
            RZPOrderModel orderModel = new RZPOrderModel();
            orderModel.setOrderType("1");
            orderModel.setCarType(cartype);
            orderModel.setDeparture(txt_shang_address.getText().toString());
            orderModel.setDeplatitude(String.valueOf(mStartPosition.latitude));
            orderModel.setDeplongitude(String.valueOf(mStartPosition.longitude));
            if (adCode == null || adCode.equals("")) {
                adCode = "140100";
            }
            orderModel.setAddress(Integer.parseInt(adCode.substring(0, adCode.length() - 2) + "00"));
            orderModel.setDestination(txt_xia_address.getText().toString());
            orderModel.setDestlatitude(String.valueOf(mEndPosition.latitude));
            orderModel.setDestlongitude(String.valueOf(mEndPosition.longitude));
            addZPOrder(orderModel);
        } else {
            TastyToast.makeText(getActivity(), "定位点尚未定位成功，定位成功后，点击叫车", app.SHORT, app.WARNING);
        }
    }

    @Click
    void btn_replace() {
        RZPOrderModel orderModel = new RZPOrderModel();
        orderModel.setOrderType("1");
        orderModel.setCarType(cartype);
        orderModel.setDeparture(txt_shang_address.getText().toString());
        orderModel.setDeplatitude(String.valueOf(mStartPosition.latitude));
        orderModel.setDeplongitude(String.valueOf(mStartPosition.longitude));
        if (adCode == null || adCode.equals("")) {
            adCode = "140100";
        }
        orderModel.setAddress(Integer.parseInt(adCode.substring(0, adCode.length() - 2) + "00"));
        orderModel.setDestination(txt_xia_address.getText().toString());
        orderModel.setDestlatitude(String.valueOf(mEndPosition.latitude));
        orderModel.setDestlongitude(String.valueOf(mEndPosition.longitude));
        Intent intent = new Intent(getActivity(), RelpaceCallCarActivity_.class);
        intent.putExtra("rzpOrderModel", orderModel);
        intent.putExtra("mStartPosition", mStartPosition);
        intent.putExtra("mEndPosition", mEndPosition);
        startActivity(intent);
    }

    @Background
    void addZPOrder(RZPOrderModel orderModel) {
        ResultModel<AddZPOrderModel> res = zpOrderFinder.addZCOrder(orderModel);
        showAddResult(res);
    }

    @UiThread
    void showAddResult(ResultModel<AddZPOrderModel> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                if (res.getData() != null) {
                    AddZPOrderModel zpOrderModel = res.getData();
                    if (zpOrderModel.getIsok() == 1) {
                        modifyState();
                        Intent intent = new Intent(getActivity(), WaitForJieJiaNewActivity_.class);
                        intent.putExtra("mStartPosition", mStartPosition);
                        intent.putExtra("mEndPosition", mEndPosition);
                        intent.putExtra("orderModelDetail", zpOrderModel.getOrder());
                        startActivity(intent);
                    } else if (zpOrderModel.getIsok() == 2) {
                        new MaterialDialog.Builder(getActivity())
                                .title("提示")
                                .titleGravity(GravityEnum.CENTER)
                                .titleColorRes(R.color.colorFontGray)
                                .content("您有末支付的订单，请前往我的行程进行支付。")
                                .contentColorRes(R.color.colorFontGray)
                                .positiveText("确定")
                                .positiveColor(ContextCompat.getColor(getActivity(), R.color.colorFontBlue))
                                .buttonsGravity(GravityEnum.CENTER)
                                .show();
                    } else if (zpOrderModel.getIsok() == 3) {
                        new MaterialDialog.Builder(getActivity())
                                .title("提示")
                                .titleGravity(GravityEnum.CENTER)
                                .titleColorRes(R.color.colorFontGray)
                                .content(zpOrderModel.getMsg())
                                .contentColorRes(R.color.colorFontGray)
                                .positiveText("确定")
                                .positiveColor(ContextCompat.getColor(getActivity(), R.color.colorFontBlue))
                                .buttonsGravity(GravityEnum.CENTER)
                                .show();
                    } else if (zpOrderModel.getIsok() == 4) {
                        new MaterialDialog.Builder(getActivity())
                                .title("提示")
                                .titleGravity(GravityEnum.CENTER)
                                .titleColorRes(R.color.colorFontGray)
                                .content(zpOrderModel.getMsg())
                                .contentColorRes(R.color.colorFontGray)
                                .positiveText("确定")
                                .positiveColor(ContextCompat.getColor(getActivity(), R.color.colorFontBlue))
                                .buttonsGravity(GravityEnum.CENTER)
                                .show();
                    }
                }
            }
        }
    }

    /**
     * 移除marker
     */

    public static void removeMarkers(ArrayList<Marker> markers) {
        for (Marker marker : markers) {
            marker.remove();
            marker.destroy();
        }
        markers.clear();
    }

    public void onIsAutoLocation(int index) {
        if (index == 1) {
            mLocationTask.startLocate(8);
        } else {
            mLocationTask.stopLocate();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();
        mLocationTask.onDestroy();
        RouteTask.getInstance(getContext()).removeRouteCalculateListener(this);
        removeMarkers(markers);
        removeMarkers(carMarkers);
        mNearbySearch.destroy();

    }

    @Override
    public void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
        if (!sp.token().get().equals("")){
            isIngOrder();
        }

        if (app.index == 1) {
            if (isStart) {
                if (isChangeStartAddress) {
                    mIsFirst = true;
                    mLocationTask.startLocate(8);
                    Logger.d(mLocationTask);
                }
            } else {
                mLocationTask.stopLocate();
            }
        } else {
            mLocationTask.stopLocate();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
        mLocationTask.stopLocate();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);

    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
    }

    @Override
    public void deactivate() {
        mListener = null;
    }


    @Override
    public void onTouch(MotionEvent motionEvent) {
        mIsFirst = false;
    }
}
